<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属产品" prop="code">
        <el-cascader v-model="queryProductIds" :options="productOptions" :props="{ checkStrictly: true }" clearable></el-cascader>
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类型编号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入类型编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['device:deviceType:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['device:deviceType:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['device:deviceType:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="deviceTypeList" @selection-change="handleSelectionChange" @row-click="toSeriesIo">
      <el-table-column type="selection" width="55" align="left" />
      <el-table-column label="名称" align="left" prop="name" width="300">
        <template slot-scope="scope">
          {{scope.row.name}}
          <i18n-input :objId="scope.row.id" type="com.ems.device.DeviceType" property="deviceType.Name" slot="append"></i18n-input>
        </template>
      </el-table-column>
      <el-table-column label="类型编号" align="left" prop="code" />
      <el-table-column label="所属产品" align="left" prop="productName" />
      <el-table-column label="图标" align="center" prop="icon">
        <template slot-scope="scope">
          <img :src="getDeviceIcon(scope.row.icon)" style="width: 30px;height: 30px;vertical-align: middle;" alt="">
        </template>
      </el-table-column>
      <el-table-column label="排序号" align="center" prop="sort" />
      <el-table-column label="配置" align="center" class-name="small-padding fixed-width" width="500">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-setting"
            v-hasPermi="['device:types:config']"
            @click="reportConfig(scope.row,'station',0)"
          >统计配置</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-setting"
            v-hasPermi="['device:types:config']"
            @click="handleConfig(scope.row,'station',0)"
          >站点显示配置</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-setting"
            v-hasPermi="['device:types:config']"
            @click="handleConfig(scope.row,'detail',0)"
          >设备监控显示配置</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-setting"
            v-hasPermi="['device:types:config']"
            @click="handleConfig(scope.row,'control',1)"
          >设备监控控制配置</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-setting"
            v-hasPermi="['device:types:config']"
            @click="handleConfig(scope.row,'overview',0)"
          >总览配置</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="300">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document-copy"
            @click="copyConfig(scope.row)"
            v-hasPermi="['device:device:edit']"
          >复制</el-button>   
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="getDownloadConfig(scope.row,false)"
            v-hasPermi="['device:device:edit']"
          >下载</el-button>  
          <el-button
            size="mini"
            type="text"
            icon="el-icon-upload"
            @click="getDownloadConfig(scope.row,true)"
            v-hasPermi="['device:device:edit']"
          >导入</el-button> 
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['device:deviceType:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['device:deviceType:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改设备类型对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" style="width:80%"  placeholder="请输入名称" >
            <i18n-input :objId="form.id" type="com.ems.device.DeviceType" property="deviceType.Name" slot="append" v-if="form.id"></i18n-input>
          </el-input>
        </el-form-item>
        <el-form-item label="类型编号" prop="code">
          <el-input v-model="form.code" placeholder="请输入类型编号" />
        </el-form-item>
        <el-form-item label="所属产品" prop="productIds">
          <el-cascader v-model="productIds" :options="productOptions" :props="{ checkStrictly: true }" clearable></el-cascader>
        </el-form-item>
        <el-form-item label="所属设备协议" prop="seriesId">
          <el-select v-model="form.seriesId" placeholder="请选择所属设备协议">
            <el-option v-for="item in seriesList" :key="item.id" :value="item.id" :label="item.name" ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="支持刷新" prop="refreshEffective">
          <template>
            <el-radio v-model="form.refreshEffective" :label="1">支持</el-radio>
            <el-radio v-model="form.refreshEffective" :label="0">不支持</el-radio>
          </template>
        </el-form-item>
        <el-form-item label="排序号" prop="name">
          <el-input-number v-model="form.sort" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <div style="width: 40px;height: 40px;cursor: pointer;margin-left: 10px;" v-show="form.icon" @click="selectIcon">
            <img style="width: 100%;height: 100%;" :src="getDeviceIcon(form.icon)" alt="">
          </div>
          <el-button v-show="!form.icon" style="background-color:#03c2c2;color:#fff" @click="selectIcon" >选择</el-button>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 添加或修改设备类型对话框 -->
    <el-dialog :title="title" :visible.sync="configEnabled" width="800px" append-to-body>
      <el-form ref="form" :model="form" label-width="120px">
        <el-form-item label="配置字符串" prop="description">
          <el-input v-model="form.configStr" type="textarea"  rows="10" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="addImportConfig" v-if="importEnabled">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="选择图标" :visible.sync="iconPopup" width="800px" append-to-body>
      <div>
        <device-icon :target="targetIcon" @change="onIconChange"></device-icon>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSelect" >确 定</el-button>
        <el-button @click="iconPopup=false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import deviceIcon from '@/components/IconDevice/index.vue'
import { listDeviceType, getDeviceType, delDeviceType, addDeviceType, updateDeviceType , downloadConfig ,importConfig} from "@/api/device/deviceType";
import { optionSeries } from "@/api/device/series";
import { selectProductTree } from "@/api/device/deviceProduct";

export default {
  name: "DeviceType",
  components:{deviceIcon},
  dicts: ['t_device_product'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 设备类型表格数据
      deviceTypeList: [],
      seriesList:[],
      productOptions:[],
      productIds:[],
      queryProductIds:[],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      configEnabled:false,
      importEnabled:false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        seriesId:null,
        name: null,
        code: null,
        ancestors:null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        code: [
          { required: true, message: "类型编号不能为空", trigger: "blur" }
        ],
        signal: [
          { required: true, message: "信号显示不能为空", trigger: "blur" }
        ],
        battery: [
          { required: true, message: "电池显示不能为空", trigger: "blur" }
        ],
        softVersion: [
          { required: true, message: "软件版本号不能为空", trigger: "blur" }
        ],
        iccid: [
          { required: true, message: "物联网卡ID不能为空", trigger: "blur" }
        ],
        imei: [
          { required: true, message: "模组编号不能为空", trigger: "blur" }
        ],
        hardwareVersion: [
          { required: true, message: "固件版本号不能为空", trigger: "blur" }
        ],
        delFlag: [
          { required: true, message: "是否删除不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
      },
      iconPopup:false,
      targetIcon:''
    };
  },
  computed:{

  },
  created() {
    this.getList();
    this.getSeriesList()
    this.getProductList()
  },
  methods: {
    /** 查询设备类型列表 */
    getList() {
      this.loading = true;
      if(this.queryProductIds) this.queryParams.ancestors = this.queryProductIds.join(',')
      listDeviceType(this.queryParams).then(response => {
        this.deviceTypeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //获取系列列表
    getSeriesList(){
      optionSeries().then( res => this.seriesList = res.data)
    },
    //查询产品下拉列表
    getProductList(){
      selectProductTree({ancestors:''}).then( res => this.productOptions = res.data)
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.configEnabled  = false;
      this.form = {
        id: null,
        copyId:null,
        name: null,
        code: null,
        seriesId:null,
        productCode:null,
        icon: null,
        signal: 1,
        battery: 1,
        softVersion: 1,
        iccid: 1,
        imei: 1,
        sort:1,
        hardwareVersion: 1,
        refreshEffective:1,
        description: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.productIds = []
      this.reset();
      this.open = true;
      this.title = "添加设备类型";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      this.productIds = []
      getDeviceType(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改设备类型";
      });
    },
    copyConfig(row){
      this.reset();
      const id = row.id || this.ids
      getDeviceType(id).then(response => {
        this.form = response.data;
        this.form.copyId = id;
        this.form.id = null;
        this.open = true;
        this.title = "复制设备类型";
      });
    },
    getDownloadConfig(row,importEnabled){
      this.reset();
      const id = row.id || this.ids;
      downloadConfig(id).then(response => {
        this.form = response.data;
        this.configEnabled = true ;
        this.importEnabled = importEnabled;
        if(importEnabled)this.form.configStr = '';
        this.title = "下载设备配置";
      });
    },
    addImportConfig(){
      importConfig(this.form).then(res => {
        this.$modal.msgSuccess("操作成功!");
        this.configEnabled = false;
        this.getList();
      })
    },
    /** 提交按钮 */
    submitForm() {
      if(this.productIds) this.form.ancestors = this.productIds.join(',')
      if(this.productIds) this.form.productCode = this.productIds[this.productIds.length-1]
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateDeviceType(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDeviceType(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除设备类型编号为"' + ids + '"的数据项？').then(function() {
        return delDeviceType(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    //跳转到数据交互配置
    toSeriesIo(row,column, event){
      if(!column.property || column.property=='name') return false;
      this.$router.push({
        path: '/sysDevice/seriesIo',
        query: { seriesId: row.seriesId , deviceTypeId: row.id ,productCode : row.productCode , ancestors:row.ancestors}
      })
    },
    handleConfig(row , _position,_controlType){
      this.$router.push({
        path:'/deviceDisplayConfig/config',
        query:{
          deviceTypeId:row.id,
          name:row.name , 
          position:_position,
          controlType:_controlType
        }
      })
    },
    //统计配置
    reportConfig(row){
      this.$router.push({ path:'/report/reportConfig', query:{ deviceTypeId:row.id} })
    },
    selectIcon(){
      this.targetIcon = this.form.icon;
      this.iconPopup = true;
    },
    onIconChange(value){
      this.targetIcon = value;
    },
    handleSelect(){
      if(this.targetIcon){
        this.form.icon = this.targetIcon;
        this.iconPopup = false;
      }
    },
  }
};
</script>
